//
//  ViewController.m
//  SLNavigationSlide
//
//  Created by 深蓝 on 14/4/4.
//  Copyright (c) 2014年 SL. All rights reserved.
//


#import "SLNavigationSlideViewController.h"
#import "SlideNavigationLabel.h"
#import "UIView+HMExtension.h"
#import "NSString+Extension.h"


#define SLTitleHeight 50
#define SLTitleButtomViewHeight 5

@interface SLNavigationSlideViewController () <UIScrollViewDelegate>
/** 顶部的标题scrollView */
@property (nonatomic, strong) UIScrollView *titlesScrollView;
/** 底部的内容scrollView */
@property (nonatomic, strong) UIScrollView *contentsScrollView;

/** 标题底部的view */
@property (nonatomic, strong) UIView *titleButtomView;
@end

@implementation SLNavigationSlideViewController

#pragma mark - 实例化一个导航滚动器
+ (instancetype)navigationSlideWithTitles:(NSArray *)titles contents:(NSArray *)contents
{
    // 1.实例化自己
    SLNavigationSlideViewController *homeVc = [[SLNavigationSlideViewController alloc] init];
    
    // 2.存储顶部标题
    homeVc.titles = titles;
    
    // 3.存储底部控制器
    homeVc.contents = contents;
    
    return homeVc;
}

#pragma mark - 视图即将显示
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 1.添加所有的子控制器
    [self setupAllChildVces];
    
    // 2.处理顶部的标题scrollView
    [self setupTitlesScrollView];
    
    // 3.默认设置
    [self setupDefaultSetting];
    
}

#pragma mark - 默认设置
- (void)setupDefaultSetting
{
    // 1.显示第一个控制器
    UIView *firstView = [[self.childViewControllers firstObject] view];
    firstView.frame = self.contentsScrollView.bounds;
    [self.contentsScrollView addSubview:firstView];

    // 2.取出第一个label
    SlideNavigationLabel *firstLabel = [self.titlesScrollView.subviews firstObject];
    firstLabel.scale = 1.0;
    
    // 3.设置标题底部的view
    self.titleButtomView.frame = CGRectMake(firstLabel.x+(_margin*0.5), CGRectGetMaxY(firstLabel.frame)-SLTitleButtomViewHeight, firstLabel.width-_margin, SLTitleButtomViewHeight);
    [self.titlesScrollView addSubview:_titleButtomView];
    
}

#pragma mark - 添加所有的子控制器
- (void)setupAllChildVces
{
    // 1.创建顶部的标题scrollView
    CGFloat titleWidth = self.view.width;
    CGFloat titleHeight = SLTitleHeight;
    CGFloat titleX = 0;
    CGFloat titleY = 0;
    _titlesScrollView = [[UIScrollView alloc] init];
    _titlesScrollView.showsHorizontalScrollIndicator = NO;
    _titlesScrollView.frame = CGRectMake(titleX, titleY, titleWidth, titleHeight);
    [self.view addSubview:_titlesScrollView];
    
    // 2.创建底部的内容scrollView
    CGFloat contentWidth = self.view.width;
    CGFloat contentHeight = self.view.height - CGRectGetMaxY(_titlesScrollView.frame);
    CGFloat contentX = 0;
    CGFloat contentY = CGRectGetMaxY(_titlesScrollView.frame);
    _contentsScrollView = [[UIScrollView alloc] init];
    _contentsScrollView.pagingEnabled = YES;
    _contentsScrollView.delegate = self;
    _contentsScrollView.frame = CGRectMake(contentX, contentY, contentWidth, contentHeight);
    [self.view addSubview:_contentsScrollView];
    
    // 3.添加顶部的scrollView内容
    for (int i = 0; i<_titles.count; i++) {
        UIViewController *contentVc = _contents[i];
        contentVc.view.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1.0];
        [self addChildViewController:contentVc];
    }
    
    // 4.设置底部scrollView的内容大小
    self.contentsScrollView.contentSize = CGSizeMake(_titles.count * _contentsScrollView.width, 0);
}

#pragma mark - 处理顶部的标题scrollView
- (void)setupTitlesScrollView
{
    // 1.初始化属性值
    CGFloat labelW = 0;
    CGFloat margin = _margin;
    UIFont *font = _font;
    if (!_margin) {
        margin = 20;
    }
    if (!font) {
        font = [UIFont systemFontOfSize:20];
    }
    
    // 2.添加所有的label
    for (int i = 0; i<_titles.count; i++) {
        // 2.1 设置属性
        SlideNavigationLabel *label = [[SlideNavigationLabel alloc] init];
        label.tag = i;
        label.text = _titles[i];
        label.font = font;
        // 2.2 添加手势
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick:)]];
        
        // 2.3 计算文字宽度
        labelW = [NSString textSize:label.text maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:label.font].width + margin;

        // 2.4 取出上一个label的x
        SlideNavigationLabel *lastLabel = [_titlesScrollView.subviews lastObject];
        label.y = 0;
        label.x = CGRectGetMaxX(lastLabel.frame);
        label.height = self.titlesScrollView.frame.size.height;
        label.width = labelW;
        [self.titlesScrollView addSubview:label];
        
        label.scale = 0.0;
    }
    
    // 3.设置内容的尺寸
    SlideNavigationLabel *label = [_titlesScrollView.subviews lastObject];
    self.titlesScrollView.contentSize = CGSizeMake(CGRectGetMaxX(label.frame), 0);
}

#pragma mark - 监听顶部label的点击
- (void)labelClick:(UITapGestureRecognizer *)tap
{
    // 1.获得被点击的label
    UIView *label = tap.view;
    
    // 2.滚动contentsScrollView到当前显示的控制器
    CGFloat contentsOffsetX = label.tag * self.contentsScrollView.width;
    CGPoint contentsOffset = CGPointMake(contentsOffsetX, self.contentsScrollView.contentOffset.y);
    [self.contentsScrollView setContentOffset:contentsOffset animated:YES];
}

#pragma mark - ScrollView代理方法，触摸过程中一直调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 1.计算偏移量
    CGFloat value = ABS(scrollView.contentOffset.x / scrollView.width);
    
    // 2.左边界面的索引
    int leftIndex = value;
    // 3.右边界面的索引
    int rightIndex = leftIndex + 1;
    
    // 4.右边的比例
    CGFloat rightScale = value - leftIndex;
    // 5.左边的比例
    CGFloat leftScale = 1 - rightScale;
    
    // 6.控制字体缩放
    SlideNavigationLabel *leftLabel = self.titlesScrollView.subviews[leftIndex];
    leftLabel.scale = leftScale;
    
    // 7.修复最后一个按钮的瑕疵
    if (rightIndex >= _titles.count) return;
    SlideNavigationLabel *rightLabel = self.titlesScrollView.subviews[rightIndex];
    rightLabel.scale = rightScale;
}

#pragma mark - ScrollView代理方法，当scrollView停止滚动（减速完毕）就会调用(需要通过代码设置滚动才会调用)
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self scrollViewDidEndDecelerating:scrollView];
}

#pragma mark - ScrollView代理方法，当scrollView停止滚动（减速完毕）就会调用(要人为控制滚动才会调用)
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 1.根据偏移量计算索引
    int index = scrollView.contentOffset.x / scrollView.width;
    
    // 2.让顶部的scrollView滚动
    SlideNavigationLabel *label = self.titlesScrollView.subviews[index];
    CGFloat titlesOffsetX = label.center.x - scrollView.width * 0.5;
    
    // 2.1 移动标题底部的view
    [UIView animateWithDuration:0.5 animations:^{
        _titleButtomView.x = label.x + (_margin*0.5);
        _titleButtomView.width = label.width - _margin;
    }];
    
    // 3.对顶部scrollView越界处理
    CGFloat maxTitlesOffsetX = self.titlesScrollView.contentSize.width - self.titlesScrollView.width;
    if (titlesOffsetX < 0) {
        titlesOffsetX = 0;
    } else if (titlesOffsetX > maxTitlesOffsetX) {
        titlesOffsetX = maxTitlesOffsetX;
    }
    CGPoint titlesOffset = CGPointMake(titlesOffsetX, self.titlesScrollView.contentOffset.y);
    [self.titlesScrollView setContentOffset:titlesOffset animated:YES];
    
    // 4.拿到其他label，scale值清零
    for (SlideNavigationLabel *otherLabel in self.titlesScrollView.subviews) {
        if (label != otherLabel && [otherLabel isKindOfClass:[SlideNavigationLabel class]]) {
            otherLabel.scale = 0.0;
        }
    }
    
    // 5.添加对应控制器的view到屏幕上
    UIViewController *vc = self.childViewControllers[index];
    
    // 6.如果vc的view已经显示在屏幕上，就没必要添加
    if (vc.view.superview) return;
    
    // 7.添加子控制器的view
    vc.view.width = self.contentsScrollView.width;
    vc.view.height = self.contentsScrollView.height;
    vc.view.y = 0;
    vc.view.x = index * vc.view.width;
    [self.contentsScrollView addSubview:vc.view];
}

#pragma mark - 懒加载
- (UIView *)titleButtomView
{
    if (!_titleButtomView) {
        _titleButtomView = [[UIView alloc] init];
        _titleButtomView.backgroundColor = [UIColor redColor];
    }
    return _titleButtomView;
}

@end
